package com.mq.consumer.test;

import com.mq.common.MqConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author zhd
 * @date 2019/08/17
 *
 * 获取AMQP实时日志信息
 **/
public class ConsumerLog {

    public static void main(String[] args) {

        try {
            Connection connection = MqConnectionUtils.getConnection();

            Channel channel = connection.createChannel();

            String errors_queue = channel.queueDeclare().getQueue();
            String warnings_queue = channel.queueDeclare().getQueue();
            String info_queue = channel.queueDeclare().getQueue();

            String exchange = "amq.rabbitmq.log";

            channel.queueBind(errors_queue,
                    exchange,
                    "error");

            channel.queueBind(warnings_queue,
                    exchange,
                    "warning");

            channel.queueBind(info_queue,
                    exchange,
                    "info");

            com.rabbitmq.client.Consumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body,"UTF-8");
                    System.out.println("-----------MQ LOG-------------\n"+ message+"\n\n");
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            };


            channel.basicConsume(errors_queue, false, consumer);
            channel.basicConsume(warnings_queue, false, consumer);
            channel.basicConsume(info_queue, false, consumer);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
